#include <config.h>
#include <encoding_manager.h>
#include <string.h>
#include <stdlib.h>

static PT_EncodingOpr g_ptEncodingOprHead;

int RegisterEncodingOpr(PT_EncodingOpr ptEncodingOpr)
{
	PT_EncodingOpr ptTmp;
	if(!g_ptEncodingOprHead)
	{
		g_ptEncodingOprHead = ptEncodingOpr;
		ptEncodingOpr->ptNext = NULL;
	}
	else
	{
		ptTmp = g_ptEncodingOprHead;
		while(ptTmp->ptNext)
		{
			ptTmp = ptTmp->ptNext;
		}
		ptTmp->ptNext = ptEncodingOpr;
		ptEncodingOpr->ptNext = NULL;
	}
	return 0;
}

void ShowEncodingOpr(void)
{
	int i = 0;
	PT_EncodingOpr ptTmp = g_ptEncodingOprHead;

	while(ptTmp)
	{
		printf("%d %s \n", ++i, ptTmp->name);
		ptTmp = ptTmp->ptNext;
	}
}

PT_EncodingOpr SelectEncodingForFile(unsigned char *pucFileBufHead)
{
	PT_EncodingOpr ptTmp = g_ptEncodingOprHead;
	
	while(ptTmp)
	{
		if(ptTmp->isSupported(pucFileBufHead))
			return ptTmp;
		else
			ptTmp = ptTmp->ptNext;
	}
	return NULL;
}


int AddFontOprForEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
	PT_FontOpr ptFontOprCpy;	

	if(!ptEncodingOpr || !ptFontOpr)
	{
		return -1;
	}
	else
	{
		ptFontOprCpy = malloc(sizeof(T_FontOpr));
		if(!ptFontOprCpy)
		{
			return -1;
		}
		else
		{
			memcpy(ptFontOprCpy, ptFontOpr, sizeof(T_FontOpr));
			ptFontOprCpy->ptNext = ptEncodingOpr->ptFontOprSupportedHead;
			ptEncodingOpr->ptFontOprSupportedHead = ptFontOprCpy;
			return 0;
		}
	}
}

int DelFontOprForEncoding(PT_EncodingOpr ptEncodingOpr, PT_FontOpr ptFontOpr)
{
	PT_FontOpr ptFontOprTmp;
	PT_FontOpr ptFontOprPre;

	if(!ptEncodingOpr || !ptFontOpr)
	{
		return -1;
	}
	else
	{
		ptFontOprTmp = ptEncodingOpr->ptFontOprSupportedHead;
		if(strcmp(ptFontOprTmp->name, ptFontOpr->name) == 0)
		{
			ptEncodingOpr->ptFontOprSupportedHead = ptFontOprTmp->ptNext;
			free(ptFontOprTmp);
			return 0;
		}

		ptFontOprPre = ptEncodingOpr->ptFontOprSupportedHead;
		ptFontOprTmp = ptFontOprPre->ptNext;
		while(ptFontOprTmp)
		{
			if(strcmp(ptFontOprTmp->name, ptFontOpr->name) == 0)
			{
				ptFontOprPre->ptNext = ptFontOprTmp->ptNext;
				free(ptFontOprTmp);
				return 0;
			}
			else
			{
				ptFontOprPre = ptFontOprTmp;
				ptFontOprTmp = ptFontOprTmp->ptNext;
			}
		}
	}
	return -1;
}

int EncodingInit(void)
{
	int iError;

	iError = Utf16leRegister();
	if(iError)
	{
		DBG_PRINTF("Utf16leRegister Error\n");
		return -1;
	}

	
	iError = Utf16beRegister();
	if(iError)
	{
		DBG_PRINTF("Utf16leRegister Error\n");
		return -1;
	}

	
	iError = Utf8Register();
	if(iError)
	{
		DBG_PRINTF("Utf16leRegister Error\n");
		return -1;
	}

	
	iError = AsciiRegister();
	if(iError)
	{
		DBG_PRINTF("Utf16leRegister Error\n");
		return -1;
	}
	return 0;
}






